package es.onlysolutions.gs.web.controller;

import com.google.gdata.data.BaseEntry;
import com.google.gdata.data.media.MediaFileSource;
import com.google.gdata.data.media.mediarss.MediaCategory;
import com.google.gdata.data.media.mediarss.MediaDescription;
import com.google.gdata.data.media.mediarss.MediaKeywords;
import com.google.gdata.data.media.mediarss.MediaTitle;
import com.google.gdata.data.youtube.VideoEntry;
import com.google.gdata.data.youtube.YouTubeMediaGroup;
import com.google.gdata.data.youtube.YouTubeNamespace;
import com.google.gdata.client.youtube.YouTubeService;
import es.onlysolutions.arq.core.auth.UserManager;
import es.onlysolutions.arq.core.mvc.command.AbstractCommandBean;
import es.onlysolutions.arq.core.mvc.utils.SynchronizedDateFormat;
import es.onlysolutions.gs.comm.factory.YouTubeServiceWrapper;
import es.onlysolutions.gs.comm.utils.IConstantes;
import es.onlysolutions.gs.comm.utils.VideoUtils;
import es.onlysolutions.gs.comm.utils.UserSettings;
import es.onlysolutions.gs.comm.facade.VideoFacade;
import es.onlysolutions.gs.web.commandBean.UploadVideoBean;
import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.net.URL;
import java.util.GregorianCalendar;
import java.util.List;

/**
 * Controller to upload a video.
 */
public class UploadVideoController extends GSController
{
    private VideoFacade videoFacade;

    private YouTubeServiceWrapper youTubeService;
    /**
     * Date format to generate the temporary files to stored the video.
     */
    private SynchronizedDateFormat dateFormat = new SynchronizedDateFormat("dd-MM-yyyy-mm-ss-SS");

    public void setVideoFacade(VideoFacade videoFacade)
    {
        this.videoFacade = videoFacade;
    }

    public void setYouTubeService(YouTubeServiceWrapper youTubeService)
    {
        this.youTubeService = youTubeService;
    }

    protected AbstractCommandBean loadPage(HttpServletRequest httpServletRequest) throws Exception
    {
        return new UploadVideoBean();
    }

    protected ModelAndView onSubmit(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object command, BindException e) throws Exception
    {
        UploadVideoBean bean = (UploadVideoBean) command;

        youTubeService.getService().setUserCredentials(bean.getYouTubeUsername(),bean.getYouTubePassword());
        VideoEntry newEntry = new VideoEntry();

        YouTubeMediaGroup mg = newEntry.getOrCreateMediaGroup();

        //Add the category.
        MediaCategory category = new MediaCategory(YouTubeNamespace.CATEGORY_SCHEME, bean.getVideoCategoryContent());
        category.setLabel(bean.getVideoCategoryLabel());
        mg.addCategory( category );
        mg.setPrivate(true);//We only upload private videos, so only the community can access to them.
        
        //Insert the title
        MediaTitle title = new MediaTitle();
        title.setHtmlContent( bean.getVideoTitle() );
        mg.setTitle( title );

        //Set the keywords.
        MediaKeywords keywords = new MediaKeywords();
        List<String> keywordsArray = VideoUtils.getKeywordsArray(bean.getVideoKeyWords());
        for (String keyWord : keywordsArray)
        {
            keywords.addKeyword(keyWord);
        }
        mg.setKeywords(keywords);

        //Add the description
        MediaDescription description = new MediaDescription();
        description.setHtmlContent( bean.getVideoContent() );
        mg.setDescription(description);

        //Add the media source.
        String suffix = dateFormat.format(new GregorianCalendar()) + '.' + UserManager.instance().getUser().getUserLogin();
        File tmpFile = File.createTempFile("gs-", suffix);
        bean.getVideoFile().transferTo( tmpFile );//Copy to the tmp file.
        MediaFileSource ms = new MediaFileSource(tmpFile, bean.getVideoFile().getContentType());
        newEntry.setMediaSource(ms);

        //Upload the video to the YouTube Service.
        YouTubeService service = youTubeService.getService();
        service.setUserCredentials( bean.getYouTubeUsername(), bean.getYouTubePassword() );
        BaseEntry videoResult = service.insert(new URL(IConstantes.YOUTUBE.VIDEO_UPLOAD_FEED), newEntry);

        String youTubeId = VideoUtils.extractYouTubeIdFromGdataId( videoResult.getId() );

        bean.setNewYouTubeId( youTubeId );

        UserSettings userSettings = (UserSettings) UserManager.instance().getUser();
        videoFacade.addVideoNotProcessed(
                bean.getVideoTitle(),
                bean.getVideoContent(),
                bean.getVideoFile().getOriginalFilename(),
                bean.getVideoKeyWords(),
                bean.getVideoCategoryContent(),
                bean.getVideoCategoryLabel(),
                youTubeId,
                userSettings.getUser() );

        return new ModelAndView( getSuccessView(), getCommandName(), bean );
    }
}
